#include <tsin/library/BulletGenerationEvent.hpp>
#include <tsin/library/BulletGenerator.hpp>

#include <tsin/runtime/BulletRuntime.hpp>

#include <tsin/util/Logger.hpp>

#include <cstring>

using namespace tsin;

BulletGenerationEvent::BulletGenerationEvent(bool d)
        : generator(0)
{
}

BulletGenerationEvent::~BulletGenerationEvent()
{
        generator->unref();
}

DynamicObject *BulletGenerationEvent::copy()
{
        return DynamicObject::copy(new BulletGenerationEvent(true));
}

void BulletGenerationEvent::init(BulletGenerator *generator)
{
        this->generator = generator;
        generator->ref();
}

void BulletGenerationEvent::reinit()
{
        BulletGenerator *arg1 = static_cast<BulletGenerator *>(arguments[0]);

        switch(nrArguments) {
        case 1:
                if (strcmp(desp, "P") == 0)
                        init(arg1);
                break;
        }
}

DynamicEvent BulletGenerationEvent::postTick(void *data, void *priv_data)
{
         DynamicEvent ret = EVENT_NONE;
         if (priv_data != 0) {
                 BulletRuntime *bullet = static_cast<BulletRuntime *>(priv_data);
                 if (trigger(*bullet, data))
                         if (handle(*bullet, data) != this)
                                 ret |= EVENT_END;
         }
         return ret;
}

bool BulletGenerationEvent::trigger(BulletRuntime &, void *)
{
        return true;
}

BulletEvent *BulletGenerationEvent::handle(BulletRuntime &bullet, void *)
{
        float data[3];

        data[0] = bullet.x;
        data[1] = bullet.y;
        data[2] = bullet.direction / 3.14159265f * 180.0f;

        if (generator)
                generator->postTick(data);
        return this;
}

extern "C" LIBRARY_DLLEXPORT DynamicObject *bindGenerationEvent()
{
        return new BulletGenerationEvent(true);
}
